/* USER CODE BEGIN Header */
/**
 ******************************************************************************
 * @file           : main.c
 * @brief          : Main program body
 ******************************************************************************
 * @attention
 *
 * Copyright (c) 2025 STMicroelectronics.
 * All rights reserved.
 *
 * This software is licensed under terms that can be found in the LICENSE file
 * in the root directory of this software component.
 * If no LICENSE file comes with this software, it is provided AS-IS.
 *
 ******************************************************************************
 */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "dma.h"
#include "i2c.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "servo.h"
#include "key.h"
#include "stdio.h"
#include "my_uart.h"
#include "buzzer.h"
#include "PID.h"
#include "JY62.h"
#include "Bluetooth.h"
#include "motor.h"
#include "OLED.h"
#include "scheduler.h"
#include "EEPROM.h"
#include "gw_grayscale_sensor.h"
#include "mission.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
uint8_t car_mode = 0;
uint8_t stepper_mode = 0;
uint8_t motor_lock = 0; // 电机锁定状�??
uint32_t temp = 0;
float base_speed = 300.0f; // 基础速度 当speed = 100 电机速度为 10cm/s
float offset = 0.0f; // 偏移量
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
int fputc(int ch, FILE *fp)
{
  HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
  return ch;
}
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
  if (huart->Instance == huart2.Instance)
  {
    //printf("cam data callback!\n");
    __HAL_UNLOCK(huart);
    cam_uart2.receivenum = Size;
    memset(cam_uart2.receivedata, 0, sizeof(cam_uart2.receivedata));
    memcpy(cam_uart2.receivedata, cam_uart2.bufftemp, Size);
    cal_cam_receive_data(cam_uart2.receivedata, &cam_data); // 处理接收到的数据
    HAL_UARTEx_ReceiveToIdle_DMA(&huart2,cam_uart2.bufftemp, sizeof(cam_uart2.bufftemp));
  }
  else if (huart->Instance == huart5.Instance)
  {
    //printf("BT data callback!\n");
    __HAL_UNLOCK(huart);
    bt_uart5.receivenum = Size;
    memset(bt_uart5.receivedata, 0, sizeof(bt_uart5.receivedata));
    memcpy(bt_uart5.receivedata, bt_uart5.bufftemp, Size);
    BT36.data_is_fresh = 1; // 添加数据新标志位
    // BT_receive_data(&BT36, bt_uart5.bufftemp[0]); // 处理接收到的数据
    HAL_UARTEx_ReceiveToIdle_DMA(&huart5, bt_uart5.bufftemp, sizeof(bt_uart5.bufftemp)); // 重新启动DMA接收
  }
  else if (huart->Instance == huart3.Instance)
  {
    //printf("servo data callback!\n");
    __HAL_UNLOCK(huart);
    servo_uart3.receivenum = Size;
    memset(servo_uart3.receivedata, 0, sizeof(servo_uart3.receivedata));
    memcpy(servo_uart3.receivedata, servo_uart3.bufftemp, Size);
    // 处理接收到的数据

    printf ("%d %d %d %d %d %d %d \n", servo_uart3.receivedata[0], servo_uart3.receivedata[1], servo_uart3.receivedata[2], servo_uart3.receivedata[3], servo_uart3.receivedata[4], servo_uart3.receivedata[5], servo_uart3.receivedata[6]);

    HAL_UARTEx_ReceiveToIdle_DMA(&huart3, servo_uart3.bufftemp, sizeof(servo_uart3.bufftemp)); // 重新启动DMA接收
  }
  
  

}
// TIM14重装载
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
  if (htim->Instance == TIM14 && car_mode == 0) // 5ms
  {
    button_ticks(); // 按键处理
  }
  if (htim->Instance == TIM6 ) // 10ms
  {
    // 读编码器、设置速度
    //motor_proc();
  }
  if (htim->Instance == TIM7) 
  {
    //处理mission
    //printf("nowtick %d\n",HAL_GetTick());
    //sensor_read(); // 读取灰度传感器数据
    //A_mission(); // 执行任务
    
    
  }
  if (htim->Instance == TIM1) // 1ms
  {
    // servo_proc(&PID_servo);
  }
}
uint8_t LobotCheckSum(uint8_t buf[])
{
  uint8_t i;
  uint16_t temp = 0;
  for (i = 2; i < buf[3] + 2; i++) 
  {
    temp += buf[i];
  }
  temp = ~temp;
  i = (uint8_t)temp; // 修正类型
  return i;
}
void uart_test(void)
{
  uint8_t test_data = 0x55;

  uint8_t buf[6]; // 修正类型

  buf[0] = buf[1] = 0x55;
  buf[2] = 254;
  buf[3] = 3;
  buf[4] = 14;
  buf[5] = LobotCheckSum(buf);
  printf("buf[5] = %d\n", buf[5]);
  HAL_UART_Transmit(&huart3, buf, 6, 10);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  if (huart->Instance == huart4.Instance)
  {
    //printf ("jy62_call\n");
    jy61p_ReceiveData(jy62_data);
    HAL_UART_Receive_DMA(&huart4, &jy62_data, 1);
  }
  else if (huart->Instance == huart6.Instance)
  {
    //printf ("stepper_call\n");
    stepper_uart6.receivenum = 9;
    memset((uint8_t *)stepper_uart6.receivedata, 0, 9);
    memcpy((uint8_t *)stepper_uart6.receivedata, (uint8_t *)stepper_uart6.bufftemp,  9);
    // 处理接收到的数据
    Stepper_Uart_Receive();
    HAL_UART_Receive_DMA(&huart6, (uint8_t *)stepper_uart6.bufftemp,9); // 重新启动DMA接收
  }

  // if (huart->Instance == huart5.Instance)
  // {

  //   printf("HC_06_call\n");
  //   if (car_mode == 0)
  //   {
  //     car_mode = 1; // 切换到自动模�??
  //     //buzzer_on();
  //   }
  //   else if (car_mode == 1)
  //   {
  //     car_mode = 0; // 切换到手动模�??
  //     //buzzer_on();
  //   }
  //   BT_receive_data(&BT36, BT36_temp);
  //   HAL_UART_Receive_DMA(&huart5, &BT36_temp, 1);
  // }
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_UART5_Init();
  MX_USART3_UART_Init();
  MX_UART4_Init();
  MX_I2C1_Init();
  MX_USART1_UART_Init();
  MX_TIM14_Init();
  MX_I2C2_Init();
  MX_TIM6_Init();
  MX_SPI1_Init();
  MX_TIM7_Init();
  MX_USART6_UART_Init();
  MX_USART2_UART_Init();
  MX_I2C3_Init();
  MX_TIM1_Init();
  /* USER CODE BEGIN 2 */
  // servo_init(&PID_servo);
  // RGB_init(&RGB_in_car);
  //BT_init(&BT36);
  // encoder_init(&encoder);
  // PID_Init(&PID3);
  // PID_Init(&PID2);
  // HAL_TIM_PWM_Start(&htim4, TIM_CHANNEL_1);
  // HAL_TIM_PWM_Start(&htim3, TIM_CHANNEL_1);
  // HAL_TIM_PWM_Start(&htim1, TIM_CHANNEL_1);
  // HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
  // HAL_UARTEx_ReceiveToIdle_DMA(&huart3, (uint8_t *)cam_uart3.bufftemp, sizeof(cam_uart3.bufftemp));
  // HAL_UART_Receive_DMA(&huart4, &jy62_data, 1);
  // HAL_UART_Receive_DMA(&huart5, &BT36_temp, 1);
  //  __HAL_TIM_SetCompare(&htim1,TIM_CHANNEL_1,500);
  //  __HAL_TIM_SetCompare(&htim2,TIM_CHANNEL_1,500);
  //__HAL_RCC_CRC_CLK_ENABLE();
  jy62_init();
  
  //HAL_UARTEx_ReceiveToIdle_DMA(&huart5, bt_uart5.bufftemp, sizeof(bt_uart5.bufftemp)); // 使用DMA接收HC-06蓝牙模块数据                                                                     // 初始化灰度传感器
  OLED_Init();
  key_init();
  //motor_init();
  //W25QXX_first_Init(); // 如果是第一次使用，擦除2048个扇区并写入默认值
  W25QXX_Init(); // 初始化W25QXX
  //sensor_init(); // 初始化灰度传感器
  //servo1_init();
  buzzer_beep(1, 100, 100);
  Stepper_Motor_Init(); // 初始化步进电机
  HAL_TIM_Base_Start_IT(&htim14);
  // HAL_TIM_Base_Start_IT(&htim6);
  // HAL_TIM_Base_Start_IT(&htim7);
  HAL_UART_Receive_DMA(&huart4, &jy62_data, 1);
  
  //HAL_StatusTypeDef DMA_status  = HAL_UART_Receive_DMA(&huart6, (uint8_t *)stepper_uart6.bufftemp,1); // 使用DMA接收步进电机数据
  //printf("DMA status: %d\n", DMA_status);
  // HAL_UARTEx_ReceiveToIdle_DMA(&huart2, cam_uart2.bufftemp, sizeof(cam_uart2.bufftemp));
  HAL_UARTEx_ReceiveToIdle_DMA(&huart3, servo_uart3.bufftemp, sizeof(servo_uart3.bufftemp));
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    //printf("Yaw = %f\n", Yaw); 
    //BT_printf("nowtick = %d\n", HAL_GetTick());
    //printf("nowtick = %d\n", HAL_GetTick());
    //printf("x = %d, y = %d\n", x, y); // 打印x和y坐标
    scheduler_run();   // 运行调度器
    uart_test();
    HAL_Delay(1000); // 延时1秒
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
